package com.beauty.dressing.module.mine.activity;

import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.beauty.dressing.R;
import com.beauty.dressing.common.base.BaseActivity;
import com.beauty.dressing.common.bean.AddressBean;
import com.beauty.dressing.common.bean.AddressManagerBean;
import com.beauty.dressing.common.bean.BaseObserver;
import com.beauty.dressing.common.bean.BaseParse;
import com.beauty.dressing.common.bean.User;
import com.beauty.dressing.logic.control.LBController;
import com.beauty.dressing.module.mine.persenter.AddressManagerControl;
import com.beauty.dressing.module.mine.persenter.AddressManagerPresenter;
import com.beauty.dressing.rxandroid.api.ApiManager;
import com.beauty.dressing.rxandroid.rxbus.RxBus;
import com.beauty.dressing.rxandroid.rxbus.RxConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.AddressSelector;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class NewAddressActivity extends BaseActivity implements OnAddressSelectedListener {
    TextView tv_rough_address_context;
    User user;
    EditText et_detailed_address, et_name, et_phone;
    CheckBox is_default;
    PopupWindow popupWindow;
    AddressManagerBean bean = null;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_new_address);
    }

    @Override
    public void findView() {
        tv_rough_address_context = findViewById(R.id.tv_rough_address_context);
        tv_rough_address_context.setOnClickListener(this);

        et_detailed_address = findViewById(R.id.et_detailed_address);
        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        is_default = findViewById(R.id.is_default);
        TextView title_txt = findViewById(R.id.title_txt);
        title_txt.setText("地址信息");
        TextView right_txt = findViewById(R.id.right_txt);
        right_txt.setText("保存");
        right_txt.setTextColor(ContextCompat.getColor(context, R.color.white));
        right_txt.setVisibility(View.VISIBLE);
        findViewById(R.id.left_img_btn).setOnClickListener(this);
        findViewById(R.id.right_txt).setOnClickListener(this);
    }

    @Override
    public void initData() {
        user = LBController.getInstance().getCacheManager().getLoginUser();
        if (getIntent().getSerializableExtra("data") != null) {
            bean = (AddressManagerBean) getIntent().getSerializableExtra("data");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_img_btn:
                this.finish();
                break;
            case R.id.right_txt:
                //保存
                if (bean == null)
                    presenter.createAddress(user.member_id, user.token, tv_rough_address_context.getText().toString().trim()
                            , et_detailed_address.getText().toString(), et_name.getText().toString()
                            , et_phone.getText().toString(), is_default.isChecked() ? "1" : "0");
                else
                    presenter.updateAddress(user.member_id, user.token, String.valueOf(bean.getId()), tv_rough_address_context.getText().toString().trim()
                            , et_detailed_address.getText().toString(), et_name.getText().toString()
                            , et_phone.getText().toString(), is_default.isChecked() ? "1" : "0");
                break;
            case R.id.tv_rough_address_context:
                //选择地址
                showAddressPickerPop();
                break;
        }
    }

    /**
     * 显示地址选择的pop
     */
    private void showAddressPickerPop() {
        AddressSelector selector = new AddressSelector(this);
        selector.setOnAddressSelectedListener(this);
        selector.setAddressProvider(new AddressProvider() {
            @Override
            public void provideProvinces(final AddressReceiver<Province> addressReceiver) {
                Map<String, String> map = new HashMap<>();
                map.put("area_id", "1");
                map.put("token", user.token);
                ApiManager.getInstence().getAddressService().areas(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<Object, AddressBean>() {
                            @Override
                            protected void onSuccees(String message, Object data, List<AddressBean> list, BaseParse extra) {
                                ArrayList<Province> mList = new ArrayList<>();
                                for (AddressBean bean : list) {
                                    Province province = new Province();
                                    province.id = bean.getArea_id();
                                    province.name = bean.getArea_name();
                                    mList.add(province);
                                }
                                addressReceiver.send(mList);
                            }

                            @Override
                            protected void onFailed(int code, String message, Object data, List<AddressBean> list, BaseParse extra) {
                            }
                        });
            }

            @Override
            public void provideCitiesWith(int i, final AddressReceiver<City> addressReceiver) {
                Map<String, String> map = new HashMap<>();
                map.put("area_id", String.valueOf(i));
                map.put("token", user.token);
                ApiManager.getInstence().getAddressService().areas(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<Object, AddressBean>() {
                            @Override
                            protected void onSuccees(String message, Object data, List<AddressBean> list, BaseParse extra) {
                                ArrayList<City> mList = new ArrayList<>();
                                for (AddressBean bean : list) {
                                    City province = new City();
                                    province.id = bean.getArea_id();
                                    province.name = bean.getArea_name();
                                    mList.add(province);
                                }
                                addressReceiver.send(mList);
                            }

                            @Override
                            protected void onFailed(int code, String message, Object data, List<AddressBean> list, BaseParse extra) {
                            }
                        });
            }

            @Override
            public void provideCountiesWith(int i, final AddressReceiver<County> addressReceiver) {
                Map<String, String> map = new HashMap<>();
                map.put("area_id", String.valueOf(i));
                map.put("token", user.token);
                ApiManager.getInstence().getAddressService().areas(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<Object, AddressBean>() {
                            @Override
                            protected void onSuccees(String message, Object data, List<AddressBean> list, BaseParse extra) {
                                ArrayList<County> mList = new ArrayList<>();
                                for (AddressBean bean : list) {
                                    County province = new County();
                                    province.id = bean.getArea_id();
                                    province.name = bean.getArea_name();
                                    mList.add(province);
                                }
                                addressReceiver.send(mList);
                            }

                            @Override
                            protected void onFailed(int code, String message, Object data, List<AddressBean> list, BaseParse extra) {
                            }
                        });
            }

            @Override
            public void provideStreetsWith(int i, final AddressReceiver<Street> addressReceiver) {
                Map<String, String> map = new HashMap<>();
                map.put("area_id", String.valueOf(i));
                map.put("token", user.token);
                ApiManager.getInstence().getAddressService().areas(map)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<Object, AddressBean>() {
                            @Override
                            protected void onSuccees(String message, Object data, List<AddressBean> list, BaseParse extra) {
                                ArrayList<Street> mList = new ArrayList<>();
                                for (AddressBean bean : list) {
                                    Street province = new Street();
                                    province.id = bean.getArea_id();
                                    province.name = bean.getArea_name();
                                    mList.add(province);
                                }
                                addressReceiver.send(mList);
                            }

                            @Override
                            protected void onFailed(int code, String message, Object data, List<AddressBean> list, BaseParse extra) {
                            }
                        });
            }
        });


        popupWindow = new PopupWindow(this);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE && !popupWindow.isFocusable()) {
                    //如果焦点不在popupWindow上，且点击了外面，不再往下dispatch事件：
                    //不做任何响应,不 dismiss popupWindow
                    return true;
                }
                //否则default，往下dispatch事件:关掉popupWindow，
                return false;
            }
        });
        popupWindow.setContentView(selector.getView());
        Display display = getWindowManager().getDefaultDisplay();
        Point outSize = new Point();
        display.getSize(outSize);//不能省略,必须有
        int screenHeight = outSize.y;//得到屏幕的高度
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(screenHeight / 2);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAtLocation(selector.getView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


    }

    private AddressManagerPresenter presenter = new AddressManagerPresenter(new AddressManagerControl() {
        @Override
        public void showProgress() {

        }

        @Override
        public void onCreateAddress(boolean isSuccess, int code, String message) {
            super.onCreateAddress(isSuccess, code, message);
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            //修改地址成功
            RxBus.getDefault().postWithCode(RxConstants.ACTION_UPDATEADDRESS_SUCCESS);
            context.finish();
        }

        @Override
        public void onAreas(boolean isSuccess, int code, String message, List<AddressBean> list) {
            showAddressPickerPop();
        }

        @Override
        public void onUpdateAddress(boolean isSuccess, int code, String message) {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            //修改地址成功
            RxBus.getDefault().postWithCode(RxConstants.ACTION_UPDATEADDRESS_SUCCESS);
            context.finish();
        }
    });

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        String s = (province == null ? "" : province.name) +
                (city == null ? "" : city.name) +
                (county == null ? "" : county.name) +
                (street == null ? "" : street.name);
        tv_rough_address_context.setText(s);
        popupWindow.dismiss();
    }

}
